package com.byit.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.byit.constant.DefaultValue;
import com.byit.domain.AppBanner;
import com.byit.enums.PromptInfo;
import com.byit.log.ChannelType;
import com.byit.log.Log;
import com.byit.log.OperatorType;
import com.byit.msg.MessageResult;
import com.byit.service.IAppBannerService;
import com.byit.shrio.session.SessionHelper;
import com.byit.utils.MinioUtil;
import com.byit.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * banner广告 前端控制器
 *
 * @author tjm
 * @date 2019年1月2日
 */
@RestController
@RequestMapping("/api/sys/banner")
public class AppBannerController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IAppBannerService appBannerService;

    @Autowired
    private MinioUtil minioUtil;

    /**
     * 添加
     */
    @Log(title = "banner", operate = OperatorType.DATA_INSERT, channel = ChannelType.WEB_INTER)
    @PostMapping("/add")
    public Object add(HttpSession session,
                      @RequestParam("picture") String picture,
                      String url,
                      @RequestParam("title") String title,
                      @RequestParam("byOrder") Integer byOrder) {
        try {
            if (byOrder != 99){
                if (byOrder < 1 || byOrder > 5){
                    return MessageResult.error("排序位置只能是1~5");
                }
                List<AppBanner> appBanners = check(byOrder);
                for (AppBanner ab : appBanners) {
                    appBannerService.setByOrderNull(ab.getId());
                }
            }
            Long userId = SessionHelper.getUserId(session);
            AppBanner appBanner = new AppBanner();
            appBanner.setCreateTime(new Date());
            appBanner.setOperationId(userId);
            appBanner.setPicture(picture);
            appBanner.setTitle(title);
            appBanner.setUrl(url);
            appBanner.setByOrder(byOrder);
            appBanner.setUpdateTime(appBanner.getCreateTime());
            appBannerService.insert(appBanner);
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return MessageResult.error(e);
        }
    }

    /**
     * 检测是否存在该排序
     * @param byOrder
     * @return
     */
    @Log(title = "banner", operate = OperatorType.DATA_INSERT, channel = ChannelType.WEB_INTER)
    @PostMapping("/check")
    public Object checkOrder(@RequestParam("byOrder")Integer byOrder){
        List<AppBanner> appBanners = check(byOrder);
        if (appBanners.size() > 0){
            return MessageResult.error("存在该排序");
        }
        return MessageResult.success();
    }

    private List<AppBanner> check(Integer byOrder){
        Map<String,Object> param = new HashMap<>();
        param.put("is_del",0);
        param.put("by_order",byOrder);
        return appBannerService.selectByMap(param);
    }

    /**
     * 上传图片
     */
    @Log(title = "banner", operate = OperatorType.IMG_UPLOAD, channel = ChannelType.WEB_INTER)
    @PostMapping("/upload")
    public Object upload(@RequestParam("file") MultipartFile file) {
        try {
            if (null == file) {
                return MessageResult.error("文件不能为空");
            } else {
                JSONObject flg = minioUtil.uploadFile(file.getInputStream(),
                        file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")), "banner/");
                if ("1".equals(flg.getString("flag"))) {
                    return MessageResult.error("上传失败");
                } else {
                    return MessageResult.success(flg.getString("path"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return MessageResult.error(e);
        }
    }

    /**
     * 修改
     */
    @Log(title = "banner", operate = OperatorType.DATA_UPDATE, channel = ChannelType.WEB_INTER)
    @PostMapping("/update")
    public Object update(HttpSession session,
                         @RequestParam("id") Long id,
                         String picture,
                         String url,
                         String title,
                         Integer byOrder) {
        try {
            if (StringUtil.isNotNull(byOrder) && byOrder != 99){
                if (byOrder < 1 || byOrder > 5){
                    return MessageResult.error("排序位置只能是1~5");
                }
                List<AppBanner> appBanners = check(byOrder);
                for (AppBanner ab : appBanners) {
                    appBannerService.setByOrderNull(ab.getId());
                }
            }
            Long userId = SessionHelper.getUserId(session);
            AppBanner appBanner = new AppBanner();
            appBanner.setId(id);
            appBanner.setPicture(picture);
            appBanner.setTitle(title);
            appBanner.setUrl(url);
            appBanner.setByOrder(byOrder);
            appBanner.setUpdateTime(new Date());
            appBanner.setOperationId(userId);
            appBannerService.updateById(appBanner);
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return MessageResult.error(e);
        }
    }

    /**
     * 详情
     */
    @Log(title = "banner", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    @PostMapping("/details")
    public Object details(@RequestParam("id") Long id) {
        AppBanner appBanner = appBannerService.selectById(id);
        if (appBanner.getIsDel() == 1) {
            return MessageResult.error("该数据已删除");
        }
        return MessageResult.success(appBanner);
    }

    /**
     * 分页列表查询
     */
    @Log(title = "banner", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    @GetMapping("/list")
    public Object list(AppBanner appBanner,
                       @RequestParam(value = "page", defaultValue = DefaultValue.PAGE_FIRST) int page,
                       @RequestParam(value = "limit", defaultValue = DefaultValue.PAGE_SIZE) int limit) {
        Page<AppBanner> pageInfo = new Page<>(page, limit);
        EntityWrapper<AppBanner> wrapper = new EntityWrapper<>();
        wrapper.setSqlSelect("id,picture,url,title,by_order as byOrder");
        wrapper.eq("is_del", 0);
        if (StringUtil.isNotNull(appBanner.getByOrder())) {
            wrapper.eq("by_order", appBanner.getByOrder());
        }
        if (StringUtil.isNotEmpty(appBanner.getTitle())) {
            wrapper.like("title", appBanner.getTitle());
        }
        wrapper.orderBy("by_order is null");
        wrapper.orderBy("by_order");
        wrapper.orderBy("update_time",false);
        Page<AppBanner> appBannerPage = appBannerService.selectPage(pageInfo, wrapper);
        return MessageResult.warpper(PromptInfo.SYS_SECCUSS, appBannerPage);
    }

    /**
     * 逻辑删除
     */
    @Log(title = "banner", operate = OperatorType.DATA_DELETE, channel = ChannelType.WEB_INTER)
    @PostMapping("/del")
    public Object delete(HttpSession session, @RequestParam("ids") String ids) {
        Long userId = SessionHelper.getUserId(session);
        List<Long> idList = StringUtil.splitLong(ids, ",");
        for (Long id : idList) {
            AppBanner appBanner = new AppBanner();
            appBanner.setId(id);
            appBanner.setUpdateTime(new Date());
            appBanner.setOperationId(userId);
            appBanner.setIsDel(1);
            appBannerService.updateById(appBanner);
        }
        return MessageResult.success();
    }

}
